package com.dss.auto_deploy.task;

import com.dss.auto_deploy.domain.AdmProject;
import com.dss.auto_deploy.mapper.AdmProjectMapper;
import com.dss.auto_deploy.service.*;
import com.dss.auto_deploy.util.ServiceException;
import com.dss.auto_deploy.util.StringUtils;
import com.dss.auto_deploy.util.mail.MailUtil;
import com.dss.auto_deploy.util.mail.MyEmail;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.io.UnsupportedEncodingException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Description:
 * @author: dongshoushan
 */
@Component("schedulerTask")
@Slf4j
@RequiredArgsConstructor(onConstructor = @_(@Autowired))
public class SchedulerTask{

    private final IServerService serverService;
    private final IAdmDockerDeployService admDockerDeployService;
    private final IAdmDockerRegistryService admDockerRegistryService;
    private final IDeployService deployService;
    private final IAdmDbService admDbService;
    private final MailUtil mailUtil;
    private final AdmProjectMapper admProjectMapper;
    /**
     * 定时更新cpu，内存使用情况
     */
    public void updateCpu() {
        log.info("更新cpu内存信息开始执行");
        try {
            serverService.updateLinuxInfo();
        }catch (Exception e) {
        }
    }


    /**
     * @param registryId 仓库id
     * @description: 删除旧镜像
     * @author: dongshoushan
     * @date:2022-11-24 14:04:52
     */
    public void deleteOldImages(String registryId){
        serverService.deleteOldImages(registryId);
    }

    /**
     * 重启仓库
     *
     * @param registryId 注册表主键id
     */
    public void restartRegistry(String registryId){
        admDockerRegistryService.restartRegistry(Long.parseLong(registryId));
        log.info("重启仓库成功registryId:{}", registryId);
    }

    /**
     *
     * @param dbId 数据库配置id
     * @param databaseName 数据库名称
     * @param javaProjectId 后端项目id
     * @param htmlProjectId 前端项目id
     * @param namespaceId 命名空间id
     */
    public void projectLaunch(String dbId,String databaseName,String javaProjectId,String htmlProjectId,String namespaceId) {
        AdmProject admProject = admProjectMapper.selectById(javaProjectId);
        AdmProject htmlProject = admProjectMapper.selectById(htmlProjectId);
        MyEmail email = null;
        List<String> list = new ArrayList<>();
        if (StringUtils.isNotEmpty(admProject.getTeamMembersMail())){
            String teamMembersMail = admProject.getTeamMembersMail();
            String[] split = teamMembersMail.split(",");
            list.addAll(Arrays.asList(split));
        }
        if (StringUtils.isNotEmpty(htmlProject.getTeamMembersMail())){
            String teamMembersMail = htmlProject.getTeamMembersMail();
            String[] split = teamMembersMail.split(",");
            for (String s : split) {
                if (!list.contains(s)){
                    list.add(s);
                }
            }
        }
        String user = String.join(",",list);
        if (StringUtils.isNotEmpty(user)){
            email = MyEmail.builder().subject(StringUtils.format("【项目上线通知】{}",admProject.getProjectName())).receiver(user).build();
        }
        log.info("============项目:{}上线开始执行,数据库id:{},数据库名称:{},后端id：{}，前端id:{},命名空间id：{}==========",admProject.getProjectName(),dbId,databaseName,javaProjectId,htmlProjectId,namespaceId);
        try {
            if (StringUtils.isEmpty(javaProjectId) && StringUtils.isEmpty(htmlProjectId)){
                throw new ServiceException("项目上线失败,未配置前后端项目id,前端端待上线项目id不可同时为空");
            }
            if (StringUtils.isEmpty(namespaceId)){
                throw new ServiceException("命名空间不可为空");
            }
            //执行sql文件
            //if (StringUtils.isNotEmpty(dbId) && StringUtils.isNotEmpty(databaseName)){
            //    admDbService.executeSql(dbId,databaseName,Long.parseLong(javaProjectId));
            //}
            //更新后端代码(只更线上新启用的)
            if (StringUtils.isNotEmpty(javaProjectId)){
                admDockerDeployService.jobToDeploy(Long.parseLong(javaProjectId),Long.parseLong(namespaceId));
            }
            //更新前端代码
            if (StringUtils.isNotEmpty(htmlProjectId)){
                deployService.jobToDeployHtml(Long.parseLong(htmlProjectId),Long.parseLong(namespaceId));
            }
            if (email!=null){
                String text = StringUtils.format("各位同事大家好：\n      项目【{}】部署成功,请大家登录线上环境检查功能点是否正常 \n \n      备注：此邮件来自发布平台自动发送,若取消订阅请前往发布平台项目配置进行取消邮件订阅配置",admProject.getProjectName());
                email.setText(text);
                mailUtil.sendMail(email);
            }
            log.info("============项目:{}上线执行成功,数据库id:{},数据库名称:{},后端id：{}，前端id:{},命名空间id：{}==========",admProject.getProjectName(),dbId,databaseName,javaProjectId,htmlProjectId,namespaceId);
        }catch (Exception e) {
            log.error("============项目:{}上线执行失败,数据库id:{},数据库名称:{},后端id：{}，前端id:{},命名空间id：{},原因：{}==========",admProject.getProjectName(),dbId,databaseName,javaProjectId,htmlProjectId,namespaceId,e.getMessage());
            if (email!=null){
                String text = StringUtils.format("各位同事大家好：\n      项目【{}】部署失败,请相关同事及时排查,失败原因：{} \n \n       备注：此邮件来自发布平台自动发送,若取消订阅请前往发布平台项目配置进行取消邮件订阅配置",admProject.getProjectName(),e.getMessage());
                email.setText(text);
                try {
                    mailUtil.sendMail(email);
                } catch (MessagingException ex) {
                    throw new RuntimeException(ex);
                } catch (UnsupportedEncodingException ex) {
                    throw new RuntimeException(ex);
                } catch (GeneralSecurityException ex) {
                    throw new RuntimeException(ex);
                }
            }
            throw new ServiceException("项目上线失败,原因："+e.getMessage());
        }
    }


    /**
     *  top -bn 1 -i -c 运行返回
     *
     *  top - 16:12:58 up 221 days,  5:33,  0 users,  load average: 0.98, 1.13, 1.15
     * Tasks: 169 total,   2 running, 167 sleeping,   0 stopped,   0 zombie
     * %Cpu(s):  2.3 us,  6.1 sy,  0.0 ni, 90.2 id,  0.0 wa,  0.0 hi,  0.8 si,  0.8 st
     * KiB Mem : 32779936 total,  1726360 free, 28038392 used,  3015184 buff/cache
     * KiB Swap:  4194300 total,  4179216 free,    15084 used.  2650988 avail Mem
     *
     *   PID USER      PR  NI    VIRT    RES    SHR S  %CPU %MEM     TIME+ COMMAND
     * 28606 root      20   0 7081484 431652  11424 S  50.0  1.3   4880:05 java -Xms1+
     *  5600 root      20   0  162056   2232   1628 R  12.5  0.0   0:00.03 top -bn 1 +
     *  6570 root      20   0   13.7g   1.8g  11728 S   6.2  5.8 121:18.43 /usr/local+
     * 12862 root      20   0   13.8g   1.1g  11544 S   6.2  3.5 143:55.17 /usr/local+
     * 31403 root      20   0   13.6g   1.9g  11544 S   6.2  6.0  19:52.04 /usr/local+
     */


    public void yangmao(String receiver,String subject,String text) throws MessagingException, GeneralSecurityException, UnsupportedEncodingException {
        MyEmail email = MyEmail.builder().subject(subject).text(text).receiver(receiver).build();
        mailUtil.sendMail(email);
    }

}
